package cn.com.dcsgo.strategy.impl;

import cn.com.dcsgo.constant.AuthConstant;
import cn.com.dcsgo.domain.LoginSysUser;
import cn.com.dcsgo.mapper.LoginSysUserMapper;
import cn.com.dcsgo.model.SecurityUser;
import cn.com.dcsgo.strategy.LoginStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 管理端用户登录策略实现类
 *
 * @author Dcsgo
 * @since 2025/9/19 14:54
 */
@Slf4j
@Service(AuthConstant.SYS_USER_LOGIN)
public class SysUserLoginStrategy implements LoginStrategy {
    @Resource
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(
                new LambdaQueryWrapper<LoginSysUser>().eq(LoginSysUser::getUsername, username)
        );
        if (loginSysUser == null) {
            throw new InternalAuthenticationServiceException("用户名不存在");
        }
        SecurityUser securityUser = new SecurityUser();
        BeanUtils.copyProperties(loginSysUser, securityUser);
        // 设置用户登录类型为管理端登录
        securityUser.setLoginType(AuthConstant.SYS_USER_LOGIN);
        // 查询用户权限
        Set<String> perms = loginSysUserMapper.selectPermsByUserId(loginSysUser.getUserId());
        securityUser.setPerms(perms);
        return securityUser;
    }
}
